//
//  QXNLoginViewController.m
//  快医
//
//  Created by sdos on 2017/3/9.
//  Copyright © 2017年 乔现宁. All rights reserved.
//

#import "QXNLoginViewController.h"
#import "Masonry.h"
#import <MBProgressHUD.h>
#import "NSString+Hash.h"
#import "NETWorkTool.h"
#import "LeftViewController.h"

#define K_userName @"username"
#define K_password @"password"

#define RGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]

// 宏定义 随机颜色
#define RandomColor RGBColor(arc4random_uniform(255), arc4random_uniform(255), arc4random_uniform(255))


@interface QXNLoginViewController ()<UITextFieldDelegate>

@property(nonatomic,strong)UIImageView *logoView;
@property(nonatomic,strong)UIImageView *logoLable;
@property(nonatomic,strong)UITextField *account;
@property(nonatomic,strong)UITextField *password;
@property(nonatomic,strong)UIButton *loginButton;

@end

@implementation QXNLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setnav];
    [self setupUI];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewDidLoad];
    
    [self.view endEditing:YES];
}

- (void)setnav
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"home_nav_button_back"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = RGBColor(66, 197, 195);
    self.title = @"登录";
}
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupUI
{
    self.navigationController.navigationBar.translucent = NO;
    //添加控件
    [self.view addSubview:self.logoView];
    [self.view addSubview:self.logoLable];
    [self.view addSubview:self.account];
    [self.view addSubview:self.password];
    [self.view addSubview:self.loginButton];
    
    
    //约束
    [self.logoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 90));
        make.top.mas_equalTo(100);
        make.centerX.equalTo(self.view);
    }];
    
    [self.logoLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 50));
        make.top.mas_equalTo(_logoView.mas_bottom).offset(2);
        make.centerX.equalTo(self.view);
    }];
    
    [self.account mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_logoLable.mas_bottom).offset(20);
        make.leading.equalTo(self.view).offset(20);
        make.trailing.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(30);
    }];
    
    [self.password mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_account.mas_bottom).offset(20);
        make.leading.equalTo(self.view).offset(20);
        make.trailing.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(30);
    }];
    
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_password.mas_bottom).offset(40);
        make.leading.equalTo(self.view).offset(20);
        make.trailing.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(40);
    }];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark
#pragma mark -设置控件属性
- (UIImageView *)logoView
{
    if (_logoView == nil) {
        _logoView = [[UIImageView alloc] init];
        _logoView.image = [UIImage imageNamed:@"product_img_logo_nor.png"];
    }
    return _logoView;
}
- (UIImageView *)logoLable
{
    if (_logoLable == nil) {
        _logoLable = [[UIImageView alloc] init];
        _logoLable.image = [UIImage imageNamed:@"product_text_logo_nor.png"];
    }
    return _logoLable;
}
- (UITextField *)account
{
   NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
    if (_account == nil) {
        _account = [[UITextField alloc] init];
        if(name == nil) {
        _account.placeholder = @"请输入账号";
        }else {
            _account.text = name;
        }
        _account.clearButtonMode = UITextFieldViewModeWhileEditing;
        _account.borderStyle = UITextBorderStyleRoundedRect;
        
        
    }
    return _account;
}
- (UITextField *)password
{
    NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
    if (_password == nil) {
        _password = [[UITextField alloc] init];
        _password.delegate = self;
        if(password == nil) {
        _password.placeholder = @"请输入密码";
        }else{
            _password.text = password;
        }
        _password.clearButtonMode = UITextFieldViewModeWhileEditing;
        _password.borderStyle = UITextBorderStyleRoundedRect;
        
    }
    return _password;
}
- (UIButton *)loginButton
{
    if (_loginButton == nil) {
        _loginButton = [[UIButton alloc] init];
        _loginButton.backgroundColor = RGBColor(66, 197, 195);
        [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
        _loginButton.tintColor = [UIColor whiteColor];
        _loginButton.titleLabel.font = [UIFont systemFontOfSize:20];
        [_loginButton addTarget:self action:@selector(clickLoginBT) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

//点击登录按钮
- (void)clickLoginBT
{
    NSString *urlStr = @"http://localhost/php/login/login.php";
//    NSString *urlStr = @"http://iosapi.itcast.cn/carelinkQuickLogin.json.php";
    
    NSMutableDictionary* dictM = [NSMutableDictionary dictionary];
    dictM[@"username"] = self.account.text;
    dictM[@"password"] = self.password.text;
//    dictM[@"login_token"] = @"985c96ce43bb5ef69de3e1ad8afaa83f";
//    dictM[@"id"] = @"1000089";
    
    
   [[NETWorkTool sharedTool] POSTWithUrlStr:urlStr parameters:dictM success:^(NSDictionary* data) {
       
       [self loginsucces];
       
       [self saveUserInfo];
       //登录成功后,把用户名和密码保存
       NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
       [userDefaults setObject:self.account.text forKey:@"username"];
       [userDefaults setObject:self.password.text forKey:@"password"];
       [userDefaults synchronize];
       
   } failure:^(NSError *error) {
    
       [self logiNfault];
   }];
    
}

- (void)saveUserInfo {
    // 缓存用户名
    [[NSUserDefaults standardUserDefaults] setObject:self.account.text forKey:K_userName];
    
    // 缓存密码前需要加密
    NSString *encodePsd = [self base64Encode:self.password.text];
    [[NSUserDefaults standardUserDefaults] setObject:encodePsd forKey:K_password];
}

//获取请求体主方法
- (NSData *)getHTTPBody{
    
//    NSString *encodePsd = [self.password.text md5String];
    NSString *body = [NSString stringWithFormat:@"userName = %@ & password = %@",self.account.text,self.password.text];
    // 把字符串快速转成二进制
    NSData *HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
    
    return HTTPBody;
}
#pragma mark - base64编码
- (NSString *)base64Encode:(NSString *)str {
    
    // 1.把字符串转成二进制
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    // 2.把二进制进行base64编码,结果就是编码之后的字符串 (编码)
    NSString *encodeStr = [data base64EncodedStringWithOptions:0];
    
    // 3.返回编码的字符串
    return encodeStr;
}
#pragma mark - Base64解码
- (NSString *)base64Decode:(NSString *)encodeStr {
    
    if (encodeStr.length == 0) {
        return nil;
    }
    
    // 1.需要把编码后的字符串转成二进制 (解码)
    // encodeStr : 当该参数为空时会崩溃
    NSData *data = [[NSData alloc] initWithBase64EncodedString:encodeStr options:0];
    
    // 2.把二进制转成字符串
    NSString *decodeStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    // 3.返回解码后的字符串
    return decodeStr;
}



#pragma mark
#pragma mark - 登录成功失败弹框
- (void)loginsucces
{
    [self.navigationController popViewControllerAnimated:YES];
    
    //登录成功弹框
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    UIImage *image = [[UIImage imageNamed:@"Checkmark"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    hud.customView = [[UIImageView alloc] initWithImage:image];
    hud.square = YES;
    hud.label.text = NSLocalizedString(@"登录成功", @"HUD done title");
    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.backgroundView.color = [UIColor colorWithWhite:0.1f alpha:0.1f];
    [hud hideAnimated:YES afterDelay:1.f];
}
- (void)logiNfault
{
    [self.navigationController popViewControllerAnimated:YES];
    
    //登录失败弹框
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    UIImage *image = [[UIImage imageNamed:@"compose_photo_close"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    hud.customView = [[UIImageView alloc] initWithImage:image];
    hud.square = YES;
    hud.label.text = NSLocalizedString(@"登录失败", @"HUD done title");
    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.backgroundView.color = [UIColor colorWithWhite:0.1f alpha:0.1f];
    [hud hideAnimated:YES afterDelay:1.f];
}

#pragma mark
#pragma mark -textField的代理方法
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    //当键盘呼不出来时,手动呼出
    [self.password becomeFirstResponder];
    NSTimeInterval animationDuration = 0.5;
    [UIView beginAnimations:@"keyBoard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动
    self.view.frame = CGRectMake(0, -100,self.view.frame.size.width , self.view.frame.size.height);
    [UIView commitAnimations];
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    [UIView beginAnimations:@"reset" context:nil];
    [UIView setAnimationDuration:0.3];
    //恢复屏幕
    self.view.frame = CGRectMake(0, 64, self.view.frame.size.width,  self.view.frame.size.height);
    [UIView commitAnimations];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
